/*******************************************************************************
 *
 * Copyright (c) 2008-2011 ayound@gmail.com, guwei8576431@gmail.com
 * This program and the accompanying materials
 * are made available under the terms of the GNU GENERAL PUBLIC LICENSE 
 * which accompanies this distribution, and is available at
 * http://dev.perl.org/licenses/gpl1.html
 * All rights reserved.
 * 
 * Created on 2009-10-22
 *******************************************************************************/

package org.cgtw.scriptprofile.server.servlet.processor;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

import org.cgtw.scriptprofile.engine.manager.CharsetDetector;
import org.cgtw.scriptprofile.server.manager.ResourceManager;
import org.cgtw.scriptprofile.server.manager.ScriptProfileServerManager;
import org.cgtw.scriptprofile.server.servlet.ScriptProfileRequest;
import org.cgtw.scriptprofile.server.servlet.ScriptProfileResponse;
import org.cgtw.scriptprofile.server.servlet.ScriptProfileResponseInfo;

public class ScriptProcessor extends AbstractProcessor {

	public ScriptProcessor(ScriptProfileRequest request,
			ScriptProfileResponse response, ScriptProfileResponseInfo info) {
		super(request, response, info);
	}

	public void process() {
		try {
			URL url = ProcessorFactory.getRemoteURL(getRequest()
					.getRequestSource());
			String resourcePath = url.getPath();
			String realPath = ResourceManager.getInstance().createResourceFile(
					resourcePath, getInfo());
			String encoding = getInfo().getEncoding();
			if (encoding == null || "gzip".equals(encoding)) {
				CharsetDetector detector = new CharsetDetector();
				detector.detect(realPath);
				encoding = detector.getCharset();
			}
			if (encoding == null) {
				encoding = ScriptProfileServerManager.getInstance().getServer()
						.getEncoding();
			}
			getResponse().writeJsHeader(encoding);
			InputStream inputStream = new FileInputStream(realPath);

			BufferedReader scriptStream = new BufferedReader(
					new InputStreamReader(inputStream, encoding));
			String line = null;
			StringBuffer buffer = new StringBuffer();
			while ((line = scriptStream.readLine()) != null) {
				buffer.append(line).append("\n");
			}
			String scriptContent = buffer.toString();
			ScriptProfileServerManager.getInstance().getServer()
					.getCompileEngine().compileScript(realPath, scriptContent);

			String[] lines = scriptContent.split("\n");
			for (int i = 0; i < lines.length; i++) {
				String jsLine = lines[i];
				if (i == 0 && "UTF-8".equalsIgnoreCase(encoding)) {
					try {
						if (jsLine.length() > 0) {
							char ch = jsLine.charAt(0);
							if (!(Character.isLetter(ch) || ch == '/')) {
								jsLine = jsLine.substring(1);
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				getResponse().writeln(jsLine, encoding);
			}
			if(inputStream != null){
				inputStream.close();
			}
			if(scriptStream != null){
				scriptStream.close();
			}
			// here we should create local file by the remote stream

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			getResponse().close();
		}

	}
}
